package spittr.web;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import spittr.data.ISpittleRepository;
import spittr.data.Spittle;

@Controller
@RequestMapping("/spittles")
public class SpittleController
{
    private ISpittleRepository spittleRepository;

    @Autowired
    public SpittleController(ISpittleRepository spittleRepository)
    {
        this.spittleRepository = spittleRepository;
    }

    // @RequestMapping(method = RequestMethod.GET)
    // public String spittles(Model model)
    // {
    // /**
    // * Model 实际就是 Map，所以参数类型用 Map也是可以的<br>
    // * 当不指定key的时候， 会根据对象类型推断<br>
    // * 本例 就会推断 为 "spittleList"，也可以显示传入Key
    // */
    // model.addAttribute(spittleRepository.findSpittles(Long.MAX_VALUE, 20));
    // return "spittles";
    // }

    private static final String MAX_LONG_AS_STRING = "9223372036854775807";

    /**
     * 第二种写法<br>
     * Key 会根据返回值类型进行推断，本例是"spittleList"<br>
     * 逻辑视图的名称会根据请求路径进行推断，本例是"spittle"
     */
    @RequestMapping(method = RequestMethod.GET)
    public List<Spittle> spittles(@RequestParam(value = "max", defaultValue = MAX_LONG_AS_STRING) Long max,
            @RequestParam(value = "count", defaultValue = "20") int count)
    {
        return spittleRepository.findSpittles(max, count);
    }

    @RequestMapping(value = "/{spittleId}", method = RequestMethod.GET)
    /**
     * @param spittleId
     *            PathVariable可以显示指定名称，如果不指定就用参数名
     * @return
     */
    public String spittle(@PathVariable long spittleId, Model model)
    {
        model.addAttribute(spittleRepository.findOne(spittleId));
        return "spittle";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String saveSpittle(@Valid Spittle form) throws Exception
    {
        spittleRepository.save(form);
        return "redirect:/spittles";
    }
}
